// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init()

// 云函数入口函数
exports.main = async (event, context) => {
  // 评论创建时间
  const createdTime = Date.now()
  const wxContext = cloud.getWXContext()
  const openid = wxContext.OPENID
  // 1. 给 comments 数据库 添加评论
  const commentsDb = cloud.database().collection('comments')
  // 获取最后一条评论的 commentId
  const commentsCountData = await commentsDb.count()
  const commentsCount = commentsCountData.total
  const lastCommentData = await commentsDb.skip(commentsCount - 1).get()
  const lastCommentId = lastCommentData.data[0].commentId
  // 获取当前用于对应的 _id 值
  const usersDb = cloud.database().collection('users')
  const userData = await usersDb.where({
    openid
  }).get()
  const user = userData.data[0]
  const userId = user._id
  delete user._id
  // 添加到数据库
  await commentsDb.add({
    data: {
      _id: lastCommentId + 1,
      commentId: lastCommentId + 1,
      content: event.inputValue,
      id: userId,
      bookId: event.bookId,
      createdTime
    }
  })
  // 2. 给 user 添加评论
  user.comments.push({
    commentId: lastCommentId + 1,
    content: event.inputValue
  })
  await usersDb.where({
    openid
  }).update({
    data: user
  })
  // 3. 给 book 添加评论
  const booksDb = cloud.database().collection('books')
  const bookData = await booksDb.where({
    bookId: event.bookId
  }).get()
  const book = bookData.data[0]
  delete book._id
  book.comments.push({
    commentId: lastCommentId + 1,
    content: event.inputValue
  })
  await booksDb.where({
    bookId: event.bookId
  }).update({
    data: book
  })
  return {
    status: 0,
    msg: '评论完成！',
    data: {
      commentId: lastCommentId + 1,
      content: event.inputValue
    }
  }
}